<template>
  <div class="multi-org-dashboard">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>多组织管理仪表板</h1>
      <p>统一管理您的所有公司业务数据</p>
    </div>

    <!-- 组织选择器 -->
    <div class="organization-selector">
      <el-card class="selector-card">
        <div class="selector-header">
          <h3>组织选择</h3>
          <el-button 
            type="primary" 
            @click="toggleSelectAll"
            size="small"
          >
            {{ selectedOrgIds.length === organizations.length ? '取消全选' : '全选' }}
          </el-button>
        </div>
        <div class="organization-grid">
          <el-checkbox-group v-model="selectedOrgIds">
            <el-checkbox 
              v-for="org in organizations" 
              :key="org.id" 
              :label="org.id"
              class="org-checkbox"
            >
              <div class="org-item">
                <el-avatar :size="32" :src="org.avatar">{{ org.name.charAt(0) }}</el-avatar>
                <span class="org-name">{{ org.name }}</span>
                <el-tag 
                  :type="org.status === 'active' ? 'success' : 'info'" 
                  size="mini"
                >
                  {{ org.status === 'active' ? '运营中' : '已停用' }}
                </el-tag>
              </div>
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <div class="selector-footer">
          <el-button 
            type="primary" 
            @click="analyzeSelectedOrganizations"
            :disabled="selectedOrgIds.length === 0"
          >
            开始分析
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 分析结果 -->
    <div v-if="analysisData" class="analysis-results">
      <!-- 统计概览 -->
      <el-row :gutter="20" class="stats-overview">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" :style="{ backgroundColor: '#409eff' }">
                <el-icon><OfficeBuilding /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ analysisData.totalOrganizations }}</div>
                <div class="stat-label">组织数量</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" :style="{ backgroundColor: '#67c23a' }">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ analysisData.totalUsers }}</div>
                <div class="stat-label">总用户数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" :style="{ backgroundColor: '#e6a23c' }">
                <el-icon><Money /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">¥{{ formatCurrency(analysisData.totalRevenue) }}</div>
                <div class="stat-label">总收入</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" :style="{ backgroundColor: '#f56c6c' }">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ analysisData.growthRate }}%</div>
                <div class="stat-label">增长率</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表展示 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>各组织收入对比</span>
              </div>
            </template>
            <div ref="revenueChart" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>组织成员分布</span>
              </div>
            </template>
            <div ref="memberChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import { 
  OfficeBuilding, TrendCharts, User, Money, 
  Search, Refresh 
} from '@element-plus/icons-vue'

// 类型定义
interface Organization {
  id: number
  name: string
  avatar: string
  status: string
}

interface OrgDetail {
  id: number
  name: string
  avatar: string
  suppliers: number
  customers: number
  revenue: number
  activeSuppliers: number
  activeSupplierRate?: number
  status: string
}

interface ChartData {
  name: string
  value: number
}

// 数据引用
const organizations = ref<Organization[]>([
  { id: 1, name: '北京分公司', avatar: '', status: 'active' },
  { id: 2, name: '上海分公司', avatar: '', status: 'active' },
  { id: 3, name: '广州分公司', avatar: '', status: 'active' },
  { id: 4, name: '深圳分公司', avatar: '', status: 'active' },
  { id: 5, name: '杭州分公司', avatar: '', status: 'active' },
  { id: 6, name: '成都分公司', avatar: '', status: 'inactive' },
  { id: 7, name: '武汉分公司', avatar: '', status: 'active' },
  { id: 8, name: '西安分公司', avatar: '', status: 'active' },
  { id: 9, name: '南京分公司', avatar: '', status: 'inactive' }
])

const selectedOrgIds = ref<number[]>([])
const analysisData = ref<any>(null)
const revenueChart = ref<HTMLDivElement | null>(null)
const memberChart = ref<HTMLDivElement | null>(null)
let chartInstance: echarts.ECharts | null = null
let compareChartInstance: echarts.ECharts | null = null

// 计算属性
const activeOrganizations = computed(() => {
  return organizations.value.filter(org => org.status === 'active')
})

// 方法
const toggleSelectAll = () => {
  if (selectedOrgIds.value.length === activeOrganizations.value.length) {
    selectedOrgIds.value = []
  } else {
    selectedOrgIds.value = activeOrganizations.value.map(org => org.id)
  }
}

const analyzeSelectedOrganizations = async () => {
  if (selectedOrgIds.value.length === 0) {
    ElMessage.warning('请至少选择一个组织')
    return
  }

  try {
    // 模拟加载分析数据
    analysisData.value = {
      totalOrganizations: selectedOrgIds.value.length,
      totalUsers: selectedOrgIds.value.length * 25,
      totalRevenue: selectedOrgIds.value.length * 1000000,
      growthRate: (Math.random() * 20).toFixed(2)
    }

    // 初始化图表
    await nextTick()
    initCharts()
  } catch (error) {
    console.error('分析组织数据失败:', error)
    ElMessage.error('分析组织数据失败')
  }
}

const initCharts = () => {
  if (revenueChart.value) {
    if (chartInstance) {
      chartInstance.dispose()
    }
    
    chartInstance = echarts.init(revenueChart.value)
    
    const option = {
      title: {
        text: '各组织收入对比',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '收入',
          type: 'pie',
          radius: '55%',
          center: ['50%', '60%'],
          data: selectedOrgIds.value.map(id => {
            const org = organizations.value.find(o => o.id === id)
            return {
              name: org?.name || '',
              value: Math.floor(Math.random() * 1000000) + 100000
            }
          }),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    
    chartInstance.setOption(option)
  }

  if (memberChart.value) {
    if (compareChartInstance) {
      compareChartInstance.dispose()
    }
    
    compareChartInstance = echarts.init(memberChart.value)
    
    const option = {
      title: {
        text: '组织成员分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: selectedOrgIds.value.map(id => {
          const org = organizations.value.find(o => o.id === id)
          return org?.name || ''
        })
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '成员数',
          type: 'bar',
          barWidth: '60%',
          data: selectedOrgIds.value.map(() => Math.floor(Math.random() * 100) + 10),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#2378f7' },
                { offset: 0.7, color: '#2378f7' },
                { offset: 1, color: '#83bff6' }
              ])
            }
          }
        }
      ]
    }
    
    compareChartInstance.setOption(option)
  }
}

const formatCurrency = (value: number) => {
  return new Intl.NumberFormat('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(value)
}

// 生命周期
onMounted(() => {
  // 默认选择前4个活跃组织
  selectedOrgIds.value = activeOrganizations.value.slice(0, 4).map(org => org.id)
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    if (chartInstance) {
      chartInstance.resize()
    }
    if (compareChartInstance) {
      compareChartInstance.resize()
    }
  })
})
</script>

<style scoped>
.multi-org-dashboard {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.page-header p {
  color: #666;
  margin: 0;
}

.organization-selector {
  margin-bottom: 20px;
}

.selector-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.selector-header h3 {
  margin: 0;
}

.organization-grid {
  margin-bottom: 15px;
}

.org-checkbox {
  margin: 10px 0;
}

.org-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.org-name {
  flex: 1;
}

.selector-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.stats-overview {
  margin-bottom: 20px;
}

.stat-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #999;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

@media (max-width: 768px) {
  .stats-overview .el-col {
    margin-bottom: 15px;
  }
  
  .chart-container {
    height: 300px;
  }
}
</style>